package com.dal.elasticsearch.controller;

import cn.hutool.json.JSONUtil;
import com.dal.elasticsearch.pojo.Log;
import com.dal.elasticsearch.service.IndexService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.*;

/**
 * 创建索引
 * @ClassName IndexController
 * @Author jian
 * @Date 10:34 AM 2022/10/14
 **/
@Api
@RestController
@RequestMapping("index")
public class IndexController {

    @Autowired
    private IndexService indexService;

    @PostMapping("create")
    public String creatIndex(String indexName){
        indexService.createIndex(indexName);
        return "ok";
    }

    @PostMapping("delete")
    public String deleteIndex(String indexName){
        indexService.deleteIndex(indexName);
        return "ok";
    }

    @GetMapping("insert")
    public String insert() throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(ResourceUtils.getFile("classpath:SougouQ.log")));
        String s;
        int i = 1;
        Map<Integer,String> jsonDocs = new HashMap();
        LinkedHashMap<String, Object> linkedHashMap = new LinkedHashMap<>();
        while ((s = br.readLine()) != null) {
            String[] words = s.split(" |\t");
            System.out.println(words[0]+" "+words[1]+words[2]+words[5]);
            Log log = new Log();
            log.setId(i);
            log.setVisittime(words[0]);
            log.setUserid(words[1]);
            log.setKeywords(words[2]);
            log.setRank(Integer.parseInt(words[3]));
            log.setClicknum(Integer.parseInt(words[4]));
            log.setUrl(words[5]);
            jsonDocs.put(i, JSONUtil.toJsonStr(log));
            i++;
            if (i>1000){
                break;
            }
        }
        int start = 0;
//        while (start < jsonDocs.size()) {
//            int end = 0;
//            if (start + 1000 <= jsonDocs.size()) {
//                end = start + 1000;
//            } else {
//                end = jsonDocs.size();
//            }
//            List<Log> sublist = jsonDocs.subList(start, end);
//            indexService.indexJsonDocs("log", sublist);
//            start += 1000;
//        }
        while(start < jsonDocs.size()){

            indexService.indexJsonDocs("log", jsonDocs);
            start ++;
        }
        //indexService.indexJsonDocs("log", jsonDocs);
        br.close();
        return "ok";
    }
}
